//
//  MLSAccessToken.swift
//  MLSMircoBlog
//
//  Created by 袁航 on 15/7/30.
//  Copyright © 2015年 yuanhang. All rights reserved.

// 授权用户,并获取用户信息
import UIKit

class MLSAccessToken: NSObject, NSCoding {
    //MARK:- 用户是否已经登录
    /// 用户是否已经登录
    class var userLogon: Bool {
       return shareAccessToken != nil
    }
    //MARK:- 用户信息
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    /// 用于调用access_token，接口获取授权后的access token。
    var access_token: String?
    
    /// access_token的生命周期，单位是秒数。
    var expires_in: NSTimeInterval = 0 {
        didSet{
            // 给过期日期赋值
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 把token的授权时间转换为date
    var expiresDate: NSDate?
    
    /// 当前授权用户的UID。
    var uid: String?
    
    /// 获取用户信息的工具对象
    private static var userAccessToken: MLSAccessToken?
    
    ///  字典转模型对象方法
    ///  - parameter dict: 字典
    ///  - returns: 模型
    init(dict: [String: AnyObject]) {
        // 必须调用super.init() 保证一定有对象
        super.init()
        setValuesForKeysWithDictionary(dict)
        
        // 字典转模型后,给全局共享的用户信息赋值
        MLSAccessToken.userAccessToken = self
    }
    
    /// 防止kvc键值对不匹配出错
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    /// 需要遵守CustomStringConvertible协议才能敲出来,然后再删掉协议
    override var description: String {
        let properties = ["access_token","expires_in","uid","screen_name","avatar_large","expiresDate"]
        return "\(dictionaryWithValuesForKeys(properties))"
    }
    
    /// 请求获取用户信息
    func loadUserAccountInfo(finished: (error: NSError?) -> ()) {
        
        // 调用网络工具方法,加载用户数据
        MLSNetworkTool.sharNewworkTools.loadUserAccountInfo(uid!) { (JSONDict, error) -> () in
            
            // 如果出错,直接返回
            if error != nil {
                finished(error: error)
                return
            }
            
            // 接受返回的数据,存储用户信息
            self.screen_name = JSONDict!["screen_name"] as? String
            self.avatar_large = JSONDict!["avatar_large"] as? String
            
            // 保存用户信息
            self.saveAccessTokenInfo()
            // 调用完成回调
            finished(error: nil)
        }
    }
    
    //MARK:- 保存用户信息路径
    private static let path = ((NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("accessToken.plist"))
    

    //MARK:- 保存用户信息
    private func saveAccessTokenInfo() {

        NSKeyedArchiver.archiveRootObject(self, toFile: MLSAccessToken.path)
    }
    
    //MARK:- 获取用户信息
    class var shareAccessToken: MLSAccessToken? {
        // 如果全局共享的userAccesstoken为空,解档
        if userAccessToken == nil {
            // 如果没有保存过,解档之后还为空
            userAccessToken = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? MLSAccessToken
        }
        
        // 判断token是否过期
        if let result = userAccessToken?.expiresDate?.compare(NSDate()) {
            // 如果过期日期比当前的日期小(升序),说明过期,把全局用户信息赋值为nil
            if result == NSComparisonResult.OrderedAscending {
                userAccessToken = nil
            }
        }
        
        return userAccessToken
    }
    
    //MARK:- 归档
    func encodeWithCoder(enCoder: NSCoder) {
        enCoder.encodeObject(screen_name, forKey: "screen_name")
        enCoder.encodeObject(avatar_large, forKey: "avatar_large")
        enCoder.encodeObject(access_token, forKey: "access_token")
        enCoder.encodeDouble(expires_in, forKey: "expires_in")
        enCoder.encodeObject(expiresDate, forKey: "expiresDate")
        enCoder.encodeObject(uid, forKey: "uid")
    }
    //MARK:- 解档
    required init?(coder deCoder: NSCoder) {
       screen_name = deCoder.decodeObjectForKey("screen_name") as? String
       avatar_large = deCoder.decodeObjectForKey("avatar_large") as? String
       access_token = deCoder.decodeObjectForKey("access_token") as? String
       expires_in = deCoder.decodeDoubleForKey("expires_in") 
       expiresDate = deCoder.decodeObjectForKey("expiresDate") as? NSDate
       uid = deCoder.decodeObjectForKey("uid") as? String
    }
    
}
